import { routerRedux } from 'dva/router';
import { stringify, parse } from 'qs';
import { reloadAuthorized } from '@/utils/Authorized';
import { setAuthority } from '@/utils/authority';
import { accountLogin } from '@/services/api';
import { message } from 'antd';
import cookie from 'react-cookies';

export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}
const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.code === '0' && response.result && response.result.user) {
        if(response.result.flag === '1'){
          message.error(`登陆失败: ${response.result.msg}`);
        }else{
          localStorage.setItem("userInfo",JSON.stringify({
            name:(response.result.user.lastName?response.result.user.lastName:'') + (response.result.user.firstName?response.result.user.firstName:''),
            isAdmin:response.result.user.isAdmin,
            id:response.result.user.id,
            provice:response.result.user.provice,
            city:response.result.user.city,
            district:response.result.user.district
          }));

          cookie.save("user_id",response.result.user.id,{path:'/'});
          cookie.save("access_token",response.result.access_token,{path:'/'});
          // cookie.save("access_token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjExNDMzMDUsInVzZXJfbmFtZSI6Im1wIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6ImY3OGUzYTg1LTAwMDYtNDQ5NC05OTRjLTc5MDViZWVmNmMwYyIsImNsaWVudF9pZCI6Inp1dWwtZ2F0ZXdheSIsInNjb3BlIjpbInJlYWQiXX0.9jO_QJyI6LlxWQmVZfxhvDQS-YSPFFafXVPUxWRqwj4",{path:'/'});

          reloadAuthorized();
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params;
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              redirect = null;
            }
          }
          // yield put(routerRedux.replace(redirect || '/'));
          yield put(routerRedux.replace( '/'));
        }
      }
    },
    *logout(_, { put }) {
      cookie.remove("user_id",{ path: '/' });
      cookie.remove("access_token",{ path: '/' });

      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      const { redirect } = getPageQuery(); // redirect

      localStorage.setItem("userInfo",null);
      if (window.location.pathname !== '/user/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          }),
        );
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      if(payload && payload.result && payload.result.user){
        if(payload.result.user.isAdmin === 0){
          setAuthority('admin');
        }else{
          setAuthority('user');
        }
      }else if(payload.currentAuthority){
        setAuthority(payload.currentAuthority);
      }else{
        setAuthority('guest');
      }


      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
